﻿
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using Labthink.PCSoft.UniversalHost4.Model.Unit;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;
using Microsoft.Win32;
using Newtonsoft.Json;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    public partial class UcUnits
    {
        public ObservableCollection<Units> UnitSysCollection =
            new ObservableCollection<Units>();

        private NotifyManager _notify;
        public UcUnits()
        {
            InitializeComponent();
            var rd = Resources.MergedDictionaries.SingleOrDefault(r => r.Source != null && r.Source.OriginalString.Contains("default.xaml"));
            if (rd != null) Resources.MergedDictionaries.Remove(rd);
        }

        private void UcUnits_OnLoaded(object sender, RoutedEventArgs e)
        {
            var w = Window.GetWindow(this);
            _notify = NotifyManager.InstanceManager(w);

            DgUnitSys.ItemsSource = UnitSysCollection;
            LoadUnitsInfo();
        }

        public string Title { get; set; } = LanguageManager.GetLanguageValue("UnitSetting");

        public string PermissionCode { get; set; } = "Per_MultiUnitSetting";

        private async void btnSetDefault_Click(object sender, RoutedEventArgs e)
        {
            if (DgUnitSys.SelectedIndex < 0)
            {
                //MessageBox.Show(LanguageManager.GetLanguageValue("Hint_SelectOneRecord"));
                _notify.ShowError(LanguageManager.GetLanguageValue("Hint_SelectOneRecord"));
                return;
            }

            _triggerButtonsStatus(false);

            var units = new Units
            {
                Id = ((Units)DgUnitSys.SelectedItem).Id,
                UnitName = ((Units)DgUnitSys.SelectedItem).UnitName,
                UnitCode = ((Units)DgUnitSys.SelectedItem).UnitCode,
                IsDefault = true
            };

            var sd = await Common.Instrument.Commands.SetDefaultUnitSysAsync(units);
            if (sd.ErrorCode < 0)
            {
                //MessageBox.Show(sd.ErrorMsg);
                _notify.ShowError(sd.ErrorMsg);
            }
            else
            {
                _notify.ShowSuccess(sd.ErrorMsg);
                TbDefaultUnitSys.Value = units.UnitName;
            }

            _triggerButtonsStatus(true);
        }

        private async void btnAddUnitSys_Click(object sender, RoutedEventArgs e)
        {
            _triggerButtonsStatus(false);
            //if (Common.IsPc)
            {
                var open = new OpenFileDialog
                {
                    Multiselect = false
                };
                var result = open.ShowDialog();
                if (result != null && result.Value)
                {
                    var file = open.FileName;
                    var str = await Common.Instrument.Commands.RestoreTestDataFromPcAsync(file);
                    _notify.ShowSuccess(str);
                }
            }
            //else
            //{
            //    var r = await InstrumentManager.CurrentInstrument.Commands.AddUnitSysAsync();
            //    if (r.ErrorCode < 0)
            //    {
            //        _notify.ShowError(r.ErrorMsg);
            //    }
            //    else
            //    {
            //        _notify.ShowSuccess(r.ErrorMsg);
            //    }
            //}
            _triggerButtonsStatus(true);
        }

        private async void btnDelUnitSys_Click(object sender, RoutedEventArgs e)
        {
            if (DgUnitSys.SelectedIndex < 0)
            {
                _notify.ShowAlarm(LanguageManager.GetLanguageValue("Hint_SelectOneRecord"));
                return;
            }

            if (TbDefaultUnitSys.Value.Equals(((Units)DgUnitSys.SelectedItem).UnitName))
            {
                _notify.ShowError(LanguageManager.GetLanguageValue("Hint_CannotDel_UnitSys"));
                return;
            }

            if (MyMessageBox.Show(Window.GetWindow(this), LanguageManager.GetLanguageValue("Confirm_DelUnitSys"), MyMessageBoxButton.OkCancel, MyMessageBoxImage.Warning, MyMessageBoxDefaultButton.Ok) != MyMessageBoxResult.Ok) return;
            _triggerButtonsStatus(false);

            var units = new Units
            {
                Id = ((Units)DgUnitSys.SelectedItem).Id,
                UnitName = ((Units)DgUnitSys.SelectedItem).UnitName,
                IsDefault = false
            };

            var sd = await Common.Instrument.Commands.DeleteUnitSysAsync(units);
            if (sd.ErrorCode < 0)
            {
                _notify.ShowError(sd.ErrorMsg);
            }

            LoadUnitsInfo();
            _triggerButtonsStatus(true);
        }

        private async void LoadUnitsInfo()
        {
            UnitSysCollection.Clear();
            DgUnitSys.Items.Refresh();

            var sd = await Common.Instrument.Commands.GetUnitSysInfoAsync();
            if (sd.ErrorCode < 0)
            {
                _notify.ShowError(sd.ErrorMsg);
            }
            else
            {
                var r = sd.Value;
                if (!string.IsNullOrEmpty(r))
                {
                    var unitsInfo = JsonConvert.DeserializeObject<List<Units>>(r);

                    foreach (var unit in unitsInfo)
                    {
                        UnitSysCollection.Add(unit);
                        if (unit.IsDefault) TbDefaultUnitSys.Value = unit.UnitName;
                    }
                }
            }
        }

        private void _triggerButtonsStatus(bool status)
        {
            BtnOk.IsEnabled = status;
            Loading.Visibility = status ? Visibility.Collapsed : Visibility.Visible;
        }
    }
}
